//
//  LoginViewController.m
//  MingShi
//
//  Created by MJiao on 15/7/1.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import "LoginViewController.h"
#import "KVNProgress.h"
#import "UserManager.h"
#import "AFHTTPRequestOperationManager.h"
#import "User.h"
#import "MingShiConfig.h"
#import "MingShiTencentSessionDelegate.h"
#import "AccountBindViewController.h"

@interface LoginViewController ()


@property(nonatomic, copy) NSString *qqAvatar;
@property(nonatomic, copy) NSString *qqNickname;
@property(nonatomic, copy) NSString *qqGender;
@end

@implementation LoginViewController
- (IBAction)btnLoginAction:(id)sender {
    NSString *account = [self.lbAccount text];
    NSString *pwd = [self.tfPwd text];

    if (account == nil || account.length == 0) {
        [KVNProgress showErrorWithStatus:@"请输入用户名"];
        [self.lbAccount becomeFirstResponder];
        return;
    }
    if (pwd == nil || pwd.length == 0) {
        [KVNProgress showErrorWithStatus:@"请输入登陆密码"];
        [self.tfPwd becomeFirstResponder];
        return;
    }
    // Adds a status below the circle
    [KVNProgress showWithStatus:@"登陆中..."];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];


    NSString *encodedAccount = [account stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/users/login?loingName=%@&pssword=%@&channelId=%@&deviceType=4", encodedAccount, pwd, [[UserManager shareUserManager] bdPushChannelId]];


    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        // 结束登陆提示
        [KVNProgress dismiss];

        NSString *code = [responseObject objectForKey:@"code"];
        //登录失败
        if (code == nil || ![code isEqualToString:@"00"]) {
            [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
            return;
        }
       
        NSArray *result = [responseObject objectForKey:@"result"];
        [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString *loingName = [obj objectForKey:@"loingName"];
            NSString *themeImage = [obj objectForKey:@"themeImage"];
            NSString *sex = [obj objectForKey:@"sex"];
            NSString *address = [obj objectForKey:@"address"];
            NSString *creatTime = [obj objectForKey:@"creatTime"];
            NSString *wenwen = [obj objectForKey:@"wenwen"];
            NSString *moneys = [obj objectForKey:@"moneys"];
            NSString *imageUrl = [obj objectForKey:@"imageUrl"];
            NSString *gradeName = [obj objectForKey:@"gradeName"];
            NSString *schoolName = [obj objectForKey:@"schoolName"];
            NSString *userName = [obj objectForKey:@"userName"];
            NSString *email = [obj objectForKey:@"email"];
            NSString *slogins = [obj objectForKey:@"slogins"];
            NSInteger userId = [[obj objectForKey:@"id"] integerValue];
            NSInteger twnum = [[obj objectForKey:@"twnum"] integerValue];
            NSInteger age = 0;

            @try {
                age = [[obj objectForKey:@"age"] integerValue];
            }
            @catch (NSException *exception) {
                NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
            }


            User *user = [[User alloc] init];
            user.account = loingName;
            user.pwd = pwd;
            user.sex = sex;
            user.address = address;
            user.creatTime = creatTime;
            user.wenwen = wenwen;
            user.moneys = moneys;
            user.imageUrl = imageUrl;
            user.gradeName = gradeName;
            user.schoolName = schoolName;
            user.userName = userName;
            user.email = email;
            user.slogins = slogins;
            user.userId = userId;
            user.twnum = twnum;
            user.age = age;
            user.themeImage = themeImage;

            [[UserManager shareUserManager] setCurUser:user];
            //保存登录信息
            [[UserManager shareUserManager] saveUserToDisk:user];
        }];
        [KVNProgress showSuccessWithStatus:@"登录成功" completion:^{

            //发送重新登陆通知
            NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
            NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
            [notificationCenter postNotificationName:@"reLoin" object:self userInfo:userInfo];

            // Things you want to do after the HUD is gone.
            [self.navigationController popToRootViewControllerAnimated:YES];
         }];
    }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        // 结束登陆提示
        [KVNProgress dismiss];
        [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
    }];
}


- (IBAction)btnSwitchAutoLoginAction:(id)sender {
    UISwitch *switchButton = (UISwitch *) sender;
    BOOL isButtonOn = [switchButton isOn];

    [[UserManager shareUserManager] setAutoLogin:isButtonOn];
}

- (void)tapDetected {

        NSArray* permissions = [NSArray arrayWithObjects:
                kOPEN_PERMISSION_GET_USER_INFO,
                kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                kOPEN_PERMISSION_GET_FANSLIST,
                kOPEN_PERMISSION_GET_IDOLLIST,
                kOPEN_PERMISSION_GET_INFO,
                kOPEN_PERMISSION_GET_OTHER_INFO,
                kOPEN_PERMISSION_GET_REPOST_LIST,
                kOPEN_PERMISSION_LIST_ALBUM,

                        nil];

    [[[MingShiTencentSessionDelegate getinstance] oauth] authorize:permissions inSafari:YES];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    /**
     *  设置开关的开闭状态
     */
    if([[UserManager shareUserManager]isAutoLogin]){
        [self.switchAutoLogin setOn: YES];
    }else{
        [self.switchAutoLogin setOn: NO];
    }

    /**
    *  判断是否安装了QQ
    */
    if (![[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
        [self.btnLoginOutlet setHidden:YES];
        [self.lbQQTip setHidden:YES];
        [self.lbOtherLoginTip setHidden:YES];
        [self.vSeparateLine setHidden:YES];
    } else {
        [self.btnLoginOutlet setHidden:NO];
        [self.lbQQTip setHidden:NO];
        [self.lbOtherLoginTip setHidden:NO];
        [self.vSeparateLine setHidden:NO];
    }
    
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected)];
    singleTap.numberOfTapsRequired = 1;

    [self.ivGoQQLogin setUserInteractionEnabled:YES];
    [self.ivGoQQLogin addGestureRecognizer:singleTap];


    /**
     *
     * 为QQ登陆注册通知事件
     */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessed) name:kLoginSuccessed object:[MingShiTencentSessionDelegate getinstance]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginFailed) name:kLoginFailed object:[MingShiTencentSessionDelegate getinstance]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(analysisResponse:) name:kGetUserInfoResponse object:[MingShiTencentSessionDelegate getinstance]];
}

#pragma mark message

- (void)analysisResponse:(NSNotification *)notify
{
    if (notify)
    {
        APIResponse *response = [[notify userInfo] objectForKey:kResponse];
        if (URLREQUEST_SUCCEED == response.retCode && kOpenSDKErrorSuccess == response.detailRetCode)
        {

            //            return;
            //头像: figureurl_qq_2
            //昵称: nickname:菜园子
            //gender:男
            NSString *avatar = [response.jsonResponse objectForKey:@"figureurl_qq_2"];
            NSString *nickname = [response.jsonResponse objectForKey:@"nickname"];
            NSString *gender = [response.jsonResponse objectForKey:@"gender"];
            NSString *city = [response.jsonResponse objectForKey:@"city"];
            NSString *province = [response.jsonResponse objectForKey:@"province"];



//            NSMutableString *str=[NSMutableString stringWithFormat:@""];
//            for (id key in response.jsonResponse)
//            {
//                [str appendString: [NSString stringWithFormat:@"%@:%@\n",key,[response.jsonResponse objectForKey:key]]];
//            }
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作成功" message:[NSString stringWithFormat:@"%@",str]
//                                  
//                                                           delegate:self cancelButtonTitle:@"我知道啦" otherButtonTitles: nil];
//            [alert show];
//
//            
//            return;
            //头像: figureurl_qq_2
            //昵称: nickname:菜园子
            //gender:男
            //  NSString* avatar =[response.jsonResponse objectForKey:@"figureurl_qq_2"];
            //  NSString* nickname =[response.jsonResponse objectForKey:@"nickname"];
            //  NSString* gender =[response.jsonResponse objectForKey:@"gender"];

            self.qqAvatar = avatar;
            self.qqNickname = nickname;
            self.qqGender = gender;
            self.qqCity = city;
            self.qqProvince = province;

            AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];

            /**
            * 验证用户是否绑定了账号
            */
            NSString *urlString = [NSString stringWithFormat:@"http://121.41.91.36:8888/api/users/verifyRegisterByQQ?openId=%@&channelId=%@&deviceType=4", [[[MingShiTencentSessionDelegate getinstance] oauth] openId], [[UserManager shareUserManager] bdPushChannelId]];

            [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

                // 结束登陆提示
                [KVNProgress dismiss];

                NSString *code = [responseObject objectForKey:@"code"];
                //登录失败
                if (code != nil && [code isEqualToString:@"00"]) {
                  //  [KVNProgress showErrorWithStatus:[responseObject objectForKey:@"msg"]];
                    NSArray *result = [responseObject objectForKey:@"result"];
                    [result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                        NSString *loingName = [obj objectForKey:@"loingName"];
                        NSString *sex = [obj objectForKey:@"sex"];
                        NSString *address = [obj objectForKey:@"address"];
                        NSString *creatTime = [obj objectForKey:@"creatTime"];
                        NSString *wenwen = [obj objectForKey:@"wenwen"];
                        NSString *moneys = [obj objectForKey:@"moneys"];
                        NSString *imageUrl = [obj objectForKey:@"imageUrl"];
                        NSString *gradeName = [obj objectForKey:@"gradeName"];
                        NSString *schoolName = [obj objectForKey:@"schoolName"];
                        NSString *email = [obj objectForKey:@"email"];
                        NSString *slogins = [obj objectForKey:@"slogins"];
                        NSInteger userId = [[obj objectForKey:@"id"] integerValue];
                        NSString *userName = [obj objectForKey:@"userName"];
                        NSString *themeImage = [obj objectForKey:@"themeImage"];


                        NSInteger age = 0;

                        @try {
                            age = [[obj objectForKey:@"brith"] integerValue];
                        }
                        @catch (NSException *exception) {
                            NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
                        }


                        NSInteger twnum = [[obj objectForKey:@"twnum"] integerValue];
                        NSString *openId = [obj objectForKey:@"openId"];
                        NSString *accessToken = [obj objectForKey:@"accessToken"];

                        User *user = [[User alloc] init];
                        user.account = loingName;
                        //user.pwd = pwd;
                        user.sex = sex;
                        user.address = address;
                        user.creatTime = creatTime;
                        user.wenwen = wenwen;
                        user.moneys = moneys;
                        user.imageUrl = imageUrl;
                        user.gradeName = gradeName;
                        user.schoolName = schoolName;
                        user.email = email;
                        user.slogins = slogins;
                        user.userId = userId;
                        user.twnum = twnum;
                        user.openId = openId;
                        user.accessToken = accessToken;
                        user.age = age;
                        user.userName = userName;
                        user.themeImage = themeImage;

                        [[UserManager shareUserManager] setCurUser:user];
                        //保存登录信息
                        [[UserManager shareUserManager] saveUserToDisk:user];
                    }];
                    [KVNProgress showSuccessWithStatus:@"登录成功" completion:^{
                        //发送重新登陆通知
                        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
                        NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
                        [notificationCenter postNotificationName:@"reLoin" object:self userInfo:userInfo];

                        // Things you want to do after the HUD is gone.
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }];
                }else{
                    //跳转到绑定界面
                    [self performSegueWithIdentifier:@"ToBindAccountSegue" sender:self];
                }
              

            }    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"Error: %@", error);
                // 结束登陆提示
                [KVNProgress dismiss];
                [KVNProgress showErrorWithStatus:@"网络异常,请稍后再试"];
            }];
            
        }
        else
        {
            NSString *errMsg = [NSString stringWithFormat:@"errorMsg:%@\n%@", response.errorMsg, [response.jsonResponse objectForKey:@"msg"]];
            [KVNProgress dismiss];
            [KVNProgress showErrorWithStatus:errMsg];
         }
    }
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"ToBindAccountSegue"]) {
        AccountBindViewController *destination = segue.destinationViewController;
        [destination setQQAvatar:self.qqAvatar];
        [destination setQQGender:self.qqGender];
        [destination setQQNickname:self.qqNickname];
        [destination setQQCity:self.qqCity];
        [destination setQQProvince:self.qqProvince];
    }
}
- (void)loginSuccessed
{
    if (NO == _isLogined)
    {
        _isLogined = YES;
    }



   NSString * openId = [[[MingShiTencentSessionDelegate getinstance] oauth] openId];
   NSString * accessToken = [[[MingShiTencentSessionDelegate getinstance] oauth] accessToken];

    NSLog(@">>>openId:%@",openId);
    NSLog(@">>>accessToken:%@",accessToken);

    [KVNProgress showWithStatus:@"数据处理中,请稍后..."];

    BOOL  ok =[[MingShiTencentSessionDelegate getinstance].oauth getUserInfo];
    if(ok){
        NSLog(@"getUserInfo is ok");
    }else{
        NSLog(@"getUserInfo is not ok");
    }

}

 

- (void)loginFailed
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"结果" message:@"登录失败" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
    [alertView show];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)btnQQLoginAction:(id)sender {
    [self tapDetected];
}
@end
